<?php
namespace web\admin\controller;

class Category extends Common{
	protected $db;
	public function __construct()
	{
		parent::__construct();
		$this->db = new \system\model\Category();
	}
	/**
	 * 分类管理器首页
	 */
	public function index(){
		//Data::tree($data, $title, $fieldPri = 'cid', $fieldPid = 'pid');
		//获取树状结构
		$data = Data::tree($this->db->get(),'cname');
		//p($data);
		//View::with 分配变量
		View::with('data',$data)->make();
	}
	/**
	 * 顶级分类管理的添加
	 */
	public function add(){
		if(IS_POST){
			if($this->db->store()){
				message('添加成功','','success');
			}
			message($this->db->getError(),'','error');
		}
		View::make();

	}
	/**
	 * 子分类添加
	 */
	public function addSon(){
		$cid = q('get.cid',0,'intval');
		if(IS_POST){
			if($this->db->store()){
				message('添加成功','','success');
			}
			message($this->db->getError(),'','error');
		}
		$cateData = $this->db->where('cid',$cid)->field(['cid','cname'])->first();
		View::with('cateData',$cateData)->make();
	}
	public function edit(){
		if (IS_POST){
			if ($this->db->edit()){
				message('操作成功','','success');
			}
			message($this->db->getError(),'','error');
		}
		$cid = q('get.cid',0,'intval');
		$oldData = $this->db->where('cid',$cid)->first();
		$cateData = $this->db->getCateData($cid);
		View::with('oldData',$oldData)->with('cateData',$cateData)->make();
	}
	public function del(){
		$cid = q('get.cid',0,'intval');
		//pluck获取单一字段
		$pid = $this->db->where('cid',$cid)->pluck('pid');
		//删除父级 修改子层级 往上升一级
		$this->db->where('pid',$cid)->update(['pid'=>$pid]);
		$this->db->where('cid',$cid)->delete();
		message('删除成功',u('index'),'success');

	}
}
